package com.bst.bsj.biz.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bst.bsj.biz.RedisLockHandler;
import com.bst.bsj.biz.RedisLockService;
import com.homewaimai.biz.cache.store.redis.IRedisTemplate;
import com.homewaimai.common.lang.Result;
import com.homewaimai.common.lang.ResultSupport;

@Service("redisLockService")
public class RedisLockServiceImpl implements RedisLockService {

    public static final Log  logger = LogFactory.getLog(RedisLockServiceImpl.class);

    @Autowired
    protected IRedisTemplate shardedJedisTemplate;

    public Result exeLock(RedisLockHandler h, String key) {
        Result r = new ResultSupport(false);

        String update_key_mux = key;
        // 添加 更新锁
        if (shardedJedisTemplate.lock(update_key_mux, "true")) {
            try {
                r = h.exec();
            } catch (Exception e) {
                logger.error("执行redis锁异常", e);
            } finally {
                shardedJedisTemplate.del(update_key_mux);
            }
        } else {
            // 如果是-1的,则删除，说明是非法key,会将整个应用锁住
            long keyTtl = shardedJedisTemplate.ttl(update_key_mux);
            if (keyTtl == -1l) {
                logger.error(update_key_mux + " ttl error,will delete!");
                shardedJedisTemplate.del(update_key_mux);
            }
            r.setDefaultModel("code", "501");
            r.setDefaultModel("data", "系统繁忙，请稍后再试");
        }

        return r;
    }

}
